<template>
  <div>
    <apexchart
      ref="chartRef"
      type="bar"
      height="350"
      :options="chartOptions"
      :series="series"
    ></apexchart>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { statisticsService } from '@/services/analysis/statistics.service';

const props = defineProps({
  engineerId: {
    type: [Number, null],
    default: null,
  },
});

const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

const chartOptions = ref({
  chart: { id: 'weekly-commits' },
  xaxis: {
    categories: days,
  },
  yaxis: [{ title: { text: '提交' } }, { opposite: true, title: { text: '代码' } }],
});
const series = ref([
  { name: '提交', data: Array(7).fill(0) },
  { name: '代码', data: Array(7).fill(0) },
]);

const chartRef = ref(null);

onMounted(fetchData);
watch(() => props.engineerId, fetchData);

async function fetchData() {
  try {
    const data = await statisticsService.getWeeklyStats(props.engineerId);
    const commits = Array(7).fill(0);
    const changes = Array(7).fill(0);
    data.forEach((item) => {
      commits[item.dayOfWeek] = item.commitCount;
      changes[item.dayOfWeek] = item.totalChanges;
    });
    series.value[0].data = commits;
    series.value[1].data = changes;
  } catch (error) {
    console.error('Error fetching weekly stats:', error);
  }
}
</script>
